﻿using MesAPI.Extensions.AuthContext;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using PublicData;
using PublicFunction;
using PublicModelsAndEntities.Entities.Function;
using PublicModelsAndEntities.Models.UserAndRole;
using XinjeMesProgram.Entities;
using XinjeMesProgram.Entities.RoleAndUser;
using XinjeMesProgram.Entities.User;

namespace MesAPI.Controllers.UserAndRole
{
    /// <summary>
    /// 角色控制器
    /// </summary>

    [Authorize]
    [ApiController]
    public class RoleController : ControllerBase
    {
        private ResponseModel response = new ResponseModel();

        /// <summary>
        /// 获取角色列表.
        /// </summary>
        /// <param name="payload">需求字段.</param>
        /// <returns> .</returns>
        [Route("/api/v1/rbac/role/List")]
        [HttpPost]
        public ResponseModel GetRolesList(RequestPayload payload)
        {

            using (FactoryMesContext factoryMes = new FactoryMesContext())
            {
                var info = from v in factoryMes.AuthRole
                            where v.CreatedByUserGuid == AuthContextService.CurrentUser.UserID
                            select new RoleBaseModel
                            {
                                Code = v.Code,
                                CreatedByUserId = v.CreatedByUserGuid,
                                CreatedOn = v.CreatedOn,
                                Description = v.Description,
                                Name = v.Name,
                                CreatedByUserName = v.CreatedByUserName,
                            };

                if (!string.IsNullOrEmpty(payload.Kw))
                {
                    info = info.Where(x => x.Name.Contains(payload.Kw));
                }

                this.response.SetData(info.OrderByDescending(x => x.CreatedOn).ToList().ListPaged(payload.CurrentPage, payload.PageSize), info.ToList().Count);
            }

            return this.response;
        }

        /// <summary>
        /// 创建角色.
        /// </summary>
        /// <param name="roleBase">需求主体.</param>
        /// <returns> .</returns>
        [Route("/api/v1/rbac/role/create")]
        [HttpPost]
        public ResponseModel CreateRole(RoleBaseModel roleBase)
        {
            if (AuthContextService.CurrentUser.UserType != UserType.SuperAdministator)
            {
                if (AuthContextService.CurrentUser.UserType != UserType.FourLevelUser)
                {
                    using (FactoryMesContext factoryMes = new FactoryMesContext())
                    {
                        var info = factoryMes.AuthRole.FirstOrDefault(x => x.Name == roleBase.Name);
                        if (info != null)
                        {
                            response.SetError("角色名称不允许重复!");
                        }
                        else
                        {
                            AuthRole authRole = new AuthRole()
                            {
                                Code = RandomHelper.GetRandomizer(8, true, false, true, true),
                                CreatedOn = DateTime.Now,
                                IsBuiltin = 0,
                                IsSuperAdministrator = 0,
                                CreatedByUserGuid = AuthContextService.CurrentUser.UserID,
                                CreatedByUserName = AuthContextService.CurrentUser.UserName,
                                IsDeleted = CommonEnum.IsDeleted.No,
                                Description = roleBase.Description,
                                Status = CommonEnum.Status.Normal,
                                Name = roleBase.Name,
                            };
                            factoryMes.AuthRole.Add(authRole);
                            factoryMes.SaveChanges();
                        }
                    }
                }
                else
                {
                    response.SetError("组员不允许创建角色");
                }
            }
            else
            {
                response.SetError("根用户不允许创建角色");
            }
            return response;
        }

        /// <summary>
        /// 编辑角色.
        /// </summary>
        /// <param name="roleBase">需求主体.</param>
        /// <returns></returns>
        [Route("/api/v1/rbac/role/Edit")]
        [HttpPost]
        public ResponseModel EditRole(RoleBaseModel roleBase)
        {

            using (FactoryMesContext factoryMes = new FactoryMesContext())
            {
                var info = factoryMes.AuthRole.FirstOrDefault(x => x.Code == roleBase.Code);
                if (info != null)
                {
                    if (info.IsBuiltin != 1)
                    {
                        if (info.Name == roleBase.Name)
                        {
                            info.IsDeleted = CommonEnum.IsDeleted.No;
                            info.Description = roleBase.Description;

                        }
                        else
                        {
                            var query = factoryMes.AuthRole.FirstOrDefault(x => x.Name == roleBase.Name);
                            if (query != null)
                            {
                                response.SetError("角色名称已被占用");
                            }
                            else
                            {
                                info.Name = roleBase.Name;
                                info.IsDeleted = CommonEnum.IsDeleted.No;
                                info.Description = roleBase.Description;
                            }
                        }
                        factoryMes.SaveChanges();
                    }
                    else
                    {
                        response.SetError("内置角色不允许修改");
                    }

                }
                else
                {
                    response.SetError("没找到该角色！");
                }
            }
            return response;
        }

        /// <summary>
        /// 删除角色--单个.
        /// </summary>
        /// <param name="ids">需求对象.</param>
        /// <returns></returns>
        [Route("/api/v1/rbac/role/delete/{ids}")]
        [HttpGet]
        public ResponseModel DeleteRole(string ids)
        {
            using (FactoryMesContext factoryMes = new FactoryMesContext())
            {
                var info = factoryMes.AuthRole.FirstOrDefault(x => x.Code == ids);
                if (info != null)
                {
                    if (info.IsBuiltin != 1)
                    {
                        string sql = string.Format("Delete from authrolepermissionmapping WHERE RoleCode='{0}'", ids);
                        if (factoryMes.Database.ExecuteSqlRaw(sql) >= 0)//if (_dbContext.Database.ExecuteSqlRaw(sql, parameters) >= 0)
                        {
                            sql = string.Format("Delete from authuserrolemapping WHERE RoleCode='{0}'", ids);
                            if (factoryMes.Database.ExecuteSqlRaw(sql) >= 0)//if (_dbContext.Database.ExecuteSqlRaw(sql, parameters) >= 0)
                            {
                                sql = string.Format("Delete from AuthRole WHERE Code='{0}'", ids);
                                if (factoryMes.Database.ExecuteSqlRaw(sql) >= 0)//if (_dbContext.Database.ExecuteSqlRaw(sql, parameters) >= 0)
                                {
                                    sql = string.Format("update MesUserRole set RoleCode = '" + string.Empty + "', IsLocked =2 where RoleCode ='{0}' ", ids);
                                    if (factoryMes.Database.ExecuteSqlRaw(sql) >= 0)
                                    {
                                        response.SetSuccess();
                                    }
                                    else
                                    {
                                        response.SetFailed();
                                    }
                                }
                            }
                            else
                            {
                                response.SetFailed();
                            }
                        }
                        else
                        {
                            response.SetFailed();
                        }
                    }
                    else
                    {
                        response.SetError("内置角色不允许删除!");
                    }
                }
            }
            return response;
        }

        /// <summary>
        /// 批量删除角色信息.
        /// </summary>
        /// <param name="command">主体.</param>
        /// <param name="ids">id.</param>
        /// <returns></returns>
        [Route("/api/v1/rbac/role/batch")]
        [HttpGet]
        public ResponseModel DeleteRoles(string command, string ids)
        {
            List<string> roleIdList = ids.Split(',').ToList();
            if (roleIdList.Any())
            {


                using (FactoryMesContext factoryMes = new FactoryMesContext())
                {
                    foreach (string id in roleIdList)
                    {

                        var info = factoryMes.AuthRole.FirstOrDefault(x => x.Code == id);
                        if (info != null)
                        {
                            if (info.IsBuiltin == 1)
                            {
                                roleIdList.Remove(id);
                            }
                        }
                    }
                    if (roleIdList.Any())
                    {
                        string parameterNames = string.Join("','", roleIdList);
                        parameterNames = "'" + parameterNames + "'";
                        string sql = string.Format("Delete from authrolepermissionmapping WHERE RoleCode IN ({0})", parameterNames);
                        if (factoryMes.Database.ExecuteSqlRaw(sql) >= 0)//if (_dbContext.Database.ExecuteSqlRaw(sql, parameters) >= 0)
                        {
                            sql = string.Format("Delete from authuserrolemapping WHERE RoleCode IN ({0})", parameterNames);
                            if (factoryMes.Database.ExecuteSqlRaw(sql) >= 0)//if (_dbContext.Database.ExecuteSqlRaw(sql, parameters) >= 0)
                            {
                                sql = string.Format("Delete from AuthRole WHERE Code IN ({0})", parameterNames);
                                if (factoryMes.Database.ExecuteSqlRaw(sql) >= 0)//if (_dbContext.Database.ExecuteSqlRaw(sql, parameters) >= 0)
                                {
                                    sql = string.Format("update MesUserRole set RoleCode = '" + string.Empty + "', IsLocked =2 where RoleCode  IN ({0}) ", parameterNames);
                                    if (factoryMes.Database.ExecuteSqlRaw(sql) >= 0)
                                    {
                                        response.SetSuccess();
                                    }
                                    else
                                    {
                                        response.SetFailed();
                                    }
                                }
                            }
                            else
                            {
                                response.SetFailed();
                            }
                        }
                        else
                        {
                            response.SetFailed();
                        }
                    }
                    else
                    {
                        response.SetError("删除的信息不能为空");
                    }
                }
            }
            else
            {
                this.response.SetError("删除的信息不能为空");
            }

            return this.response;
        }

        /// <summary>
        /// 为指定角色分配权限 v1.0.
        /// </summary>
        /// <param name="payload">角色分配权限的请求载体类.</param>
        /// <returns>操作结果.</returns>
        [Route("/api/v1/rbac/role/assign_permission")]
        [HttpPost]
        public ResponseModel AssignPermission(RoleAssignPermissionPayload payload)
        {
            if (payload.IsUserDefined)
            {
                if (!XinjeCloudUserQuery.GetUserEntity(payload.RoleCode, out MesUserRole userEntity))
                {
                    this.response.SetError("用户不存在或该用户没有自定义权限的功能");
                    return this.response;
                }
            }
            else
            {
                using var dbContext = new FactoryMesContext();
                var role = dbContext.AuthRole.FirstOrDefault(x => x.Code == payload.RoleCode);
                if (role == null)
                {
                    this.response.SetError("角色不存在");
                    return this.response;
                }
                else
                {
                    if (role.IsBuiltin == 1)
                    {
                        this.response.SetFailed("系统内置角色不能修改");
                        return this.response;
                    }
                }
            }

            if (XinjeCloudUserQuery.EditPermission(payload.RoleCode, payload.Permissions, payload.IsUserDefined, out string msg))
            {
                this.response.SetSuccess(msg);
            }
            else
            {
                this.response.SetError(msg);
            }

            return this.response;
        }
    }
}
